package com.example.iread.activity;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.iread.R;
import com.example.iread.application.MyApplication;
import com.example.iread.bean.UserBean;
import com.example.iread.dao.UserDao;
import com.example.iread.http.UserApi;
import com.example.iread.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class UserInfoActivity extends AppCompatActivity {

    private final String TAG = "SoRiya";
    private UserDao userDao;
    private ActivityResultLauncher<Intent> register;
    private View btn_set_name, btn_set_birth, btn_set_gender, btn_set_age;
    private UserBean userBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        userDao = MyApplication.getInstance().getDb().userDao();

        View btn_userinfo_close = findViewById(R.id.btn_userinfo_close);
        btn_userinfo_close.setOnClickListener(v -> finish());

        userBean = userDao.getOne();

        btn_set_name = findViewById(R.id.btn_set_name);
        btn_set_birth = findViewById(R.id.btn_set_birth);
        btn_set_gender = findViewById(R.id.btn_set_gender);
        btn_set_age = findViewById(R.id.btn_set_age);

        setText();
        eventRegister();

        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), res -> {
            Intent data = res.getData();
            if (data == null) return;
            Bundle extras = data.getExtras();
            assert extras != null;
            userBean.nickname = extras.getString("nickname");
            setText();
            saveChange();
        });

    }

    public void setText() {
        ((TextView) btn_set_name.findViewById(R.id.tv_set_name)).setText(userBean.nickname);
        ((TextView) btn_set_birth.findViewById(R.id.tv_set_birth)).setText(userBean.birthday);

        Log.i(TAG, "birthday: " + userBean.birthday);

        if (userBean.birthday == null) return;

        String[] birthday = userBean.birthday.split("-");

        String[] now = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(new Date()).split("-");

        int year = Integer.parseInt(now[0]) - Integer.parseInt(birthday[0]);
        int month = Integer.parseInt(now[1]) - Integer.parseInt(birthday[1]);
        int day = Integer.parseInt(now[2]) - Integer.parseInt(birthday[2]);

        if (month > 0) {
            year++;
        } else if (month == 0) {
            if (day > 0) {
                year++;
            }
        } else {
            year = 0;
        }

//        btn_set_age.
        ((TextView) btn_set_age.findViewById(R.id.tv_set_age)).setText(String.valueOf(year));

        ((TextView) btn_set_gender.findViewById(R.id.tv_set_gender)).setText(userBean.gender != null && userBean.gender == 0 ? "Boy" : "Girl");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z", Locale.CHINA);
        try {
            Date date = simpleDateFormat.parse(userBean.createTime.replace("Z", " UTC"));
            assert date != null;
            ((TextView) findViewById(R.id.tv_set_register)).setText(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(date));
        } catch (Exception e) {
//            throw new MyException(500, e.getMessage());
        }
    }

    public void eventRegister() {
        btn_set_name.setOnClickListener(v -> {
            Intent intent = new Intent(this, InfoEditorActivity.class);
            intent.putExtra("nickname", userBean.nickname);
            register.launch(intent);
        });

        btn_set_birth.setOnClickListener(v -> {
            DatePickerDialog datePickerDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, (datePicker, y, m, d) -> {
                userBean.birthday = String.format("%s-%s-%s", y, m + 1, d);
                setText();
                saveChange();
            }, 2019, 12, 12);
            datePickerDialog.show();
        });

        btn_set_gender.setOnClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Please select gender");
            builder.setItems(new String[]{"Boy", "Girl"}, (dialogInterface, i) -> {
                userBean.gender = i;
                setText();
                saveChange();
            });
            builder.create().show();
        });
    }

    public void saveChange() {
        userDao.update(userBean);
        UserApi.updateUserInfo(userBean, res -> {
            if (res.code == 200) ToastUtil.show(this, "Change successful");
        });
    }
}